import json
import re

# 1. 读取数据文件
input_file = "data.txt"
output_file = "output.json"

data_list = []
with open(input_file, "r") as f:
    # content = re.sub(r"\s+", "", f.read())  # \s 匹配所有空白字符（包括空格、\n、\t等）

    for line in f:
        # 2. 解析每行数据（按竖线分割）
        line = line.strip()  # 去除首尾空格/换行符
        if not line:  # 跳过空行
            continue
        name, age, city = line.split("|")  # 分割字段
        
        # 3. 构造字典并添加到列表
        data_list.append({
            "name": name,
            "age": int(age),  # 转换为整数
            "city": city
        })

# 4. 写入JSON文件
with open(output_file, "w", encoding="utf-8") as f:
    json.dump(data_list, f, indent=2, ensure_ascii=False)  # 美化输出，支持非ASCII字符

print(f"JSON文件已生成：{output_file}")